package com.outsourcing.bottle.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;

import com.outsourcing.bottle.domain.LocationEntry;

/**
 * 定位
 * @author 06peng
 *
 */
public class LocationUtil {
	
	private Context context;
	public double latitude; 
	public double longitude; 
	
	public LocationUtil(Context context) {
		this.context = context;
	}
	
	public LocationEntry locate() {
		LocationEntry entry = new LocationEntry();
		requestTelLocation();
		entry.setLatitude(latitude);
		entry.setLongitude(longitude);
		return entry;
	}
	
	private void requestTelLocation() {
		try {
			TelephonyManager mTelMan = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
			String operator = mTelMan.getNetworkOperator();
			String mcc = operator.substring(0, 3);
			String mnc = operator.substring(3);
			
			GsmCellLocation location = (GsmCellLocation) mTelMan.getCellLocation();
			int cid = location.getCid();
			int lac = location.getLac();

			JSONObject tower = new JSONObject();
			tower.put("cell_id", cid);
			tower.put("location_area_code", lac);
			tower.put("mobile_country_code", mcc);
			tower.put("mobile_network_code", mnc);
			System.out.println(">>>>>>>>>>>>>>>>" + tower.toString());
			JSONArray array = new JSONArray();
			array.put(tower);
			List<NeighboringCellInfo> list = mTelMan.getNeighboringCellInfo();
			Iterator<NeighboringCellInfo> iter = list.iterator();
			NeighboringCellInfo cellInfo;
			JSONObject tempTower;
			while (iter.hasNext()) {
				cellInfo = iter.next();
				tempTower = new JSONObject();
				try {
					tempTower.put("cell_id", cellInfo.getCid());
					tempTower.put("location_area_code", cellInfo.getLac());
					tempTower.put("mobile_country_code", mcc);
					tempTower.put("mobile_network_code", mnc);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				array.put(tempTower);
			}

			JSONObject object = createJSONObject("cell_towers", array);
			requestLocation(object);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void requestLocation(JSONObject object) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost("http://www.google.com/loc/json");
		try {
			StringEntity entity = new StringEntity(object.toString());
			post.setEntity(entity);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		try {
			HttpResponse resp = client.execute(post);
			HttpEntity entity = resp.getEntity();
			BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
			StringBuffer buffer = new StringBuffer();
			String result = br.readLine();
			while (result != null) {
				buffer.append(result);
				result = br.readLine();
			}
			JSONObject obj = new JSONObject(buffer.toString());
			JSONObject locationObj = obj.getJSONObject("location");
			latitude = locationObj.getDouble("latitude");
			longitude = locationObj.getDouble("longitude");
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private JSONObject createJSONObject(String arrayName, JSONArray array) {

		JSONObject object = new JSONObject();
		try {
			object.put("version", "1.1.0");
			object.put("host", "maps.google.com");
			object.put(arrayName, array);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return object;
	}
}
